package com.dc.es.utils;

import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonpSerializable;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import com.dc.es.bo.DocumentData;
import jakarta.json.Json;
import jakarta.json.stream.JsonGenerator;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class ESResponseUtils {




    public static <T extends JsonpSerializable> String serializeToJson(T response) {
        // 创建一个 StringWriter 用于存储 JSON 输出
        StringWriter writer = new StringWriter();
        JacksonJsonpMapper jsonpMapper = new JacksonJsonpMapper();
        // 使用 JsonWriter 将 JsonObject 写入 StringWriter
        try ( JsonGenerator generator = jsonpMapper.jsonProvider().createGenerator(writer)) {
            response.serialize(generator, jsonpMapper); // null 是 JsonpMapper，可以根据实际情况提供
        }
        // 返回 JSON 字符串
        return writer.toString();
    }

    public static <T extends JsonpSerializable> String serializeListToJson(List<T> responseList) {
        // 创建一个 StringWriter 用于存储 JSON 输出

        StringWriter writer = new StringWriter();
        JacksonJsonpMapper jsonpMapper = new JacksonJsonpMapper();
        // 使用 JsonWriter 将 JsonObject 写入 StringWriter
        try (JsonGenerator generator = jsonpMapper.jsonProvider().createGenerator(writer)) {
            generator.writeStartArray();
            for (T serializable : responseList) {
                StringWriter itemWriter = new StringWriter();
                JsonGenerator itemGenerator = jsonpMapper.jsonProvider().createGenerator(itemWriter);
                serializable.serialize(itemGenerator, jsonpMapper);
                itemGenerator.close();
                generator.write(Json.createReader(new StringReader(itemWriter.toString())).readObject());
            }
            generator.writeEnd();
        }
        // 返回 JSON 字符串
        return writer.toString();
    }


    public static <T> List<T> convertHitsToBoList(List<Hit<T>> hits) {
        List<T> boList = new ArrayList<>();
        for (Hit<T> hit : hits) {
            boList.add(hit.source());
        }
        return boList;
    }

    public static <T> List<DocumentData<T>> convertHitsToDocumentDataList(List<Hit<T>> hits) {
        List<DocumentData<T>> documentDataList = new ArrayList<>();
        for (Hit<T> hit : hits) {
            DocumentData<T> documentData = new DocumentData<>(
                    hit.id(),
                    hit.score(),
                    hit.source()
            );
            documentDataList.add(documentData);
        }
        return documentDataList;
    }
}
